package cn.zt.controller;


import cn.zt.domain.dao.User;
import cn.zt.domain.dto.LoginFormDTO;
import cn.zt.domain.pojo.Result;
import cn.zt.mapper.UserMapper;
import cn.zt.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping
public class LoginController {

    @Resource
    private IUserService userService;
    @Resource
    private UserMapper userMapper;


    /**
     * 登录功能
     * @param loginForm 登录参数，包含账号、密码
     */
    @PostMapping("/login")
    public Object login(@RequestBody LoginFormDTO loginForm, HttpSession session){
        System.out.println("loginForm:"+loginForm.getAccount() + " " + loginForm.getPassword());
        return userService.login(loginForm, session);
    }

    //退出
    @PostMapping("/logout")
    public Result logout(HttpSession session){
        Long userId = (Long) session.getAttribute("id");
        System.out.println("退出登录userId:"+userId);
        if (userId == null) {
            return Result.fail("用户未登录");
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        try {
            user.setToken(null);
            userMapper.updateById(user);
        } catch (Exception e) {
            System.out.println("退出失败，用户ID: " + userId + ", 错误信息: " + e.getMessage());
            return Result.fail("退出失败，系统错误");
        }
        return Result.ok();
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/info")
    public Result getUserInfo(String userId){

        Long id = userId == null ? null : Long.valueOf(userId);
        System.out.println("userId:"+userId);
        if (id == null) {
            return Result.fail("用户未登录");
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        return Result.ok(user.getName());
    }
}
